package com.example.service.Impl;

import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.pojo.*;
import com.example.service.AppointmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AppointmentServiceImpl implements AppointmentService {
    @Resource
    private AppointmentMapper appointmentMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OwnerMapper ownerMapper;
    @Resource
    private MessageMapper messageMapper;
//    @Resource
//    private SimpMessagingTemplate smtpMessagingTemplate;
    @Resource
    private WebSocketService webSocketService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 添加预约
     *
     * @param appointment
     */
    @Override
    public void add(Appointment appointment) {
        // 检查是否已预约

        if (isAppointment(appointment.getUserId(), appointment.getRoomId())) {
            throw new CustomException("500", "用户一天内已预约过此房间，请勿重复预约");
        }
        appointment.setStatus(0);
        appointmentMapper.add(appointment);

        // 通知房东
        Room room = roomMapper.selectById(appointment.getRoomId());
        User user = userMapper.selectById(appointment.getUserId());
        Message message  = new Message(
                "owner",
               room.getOwnerId(),
                "system-appointment",
                appointment.getId(),
                "用户："+user.getName()+"预约了您的房间："+room.getName()+"，请及时处理"
        );
        messageMapper.insert(message);

        //webSocket推送
//        webSocketService.sendMessageToOwner(message);


        // 存入Redis有序集合（用消息创建时间排序）
//        String redisKey = "owner:" + room.getOwnerId() + ":messages";
//        stringRedisTemplate.opsForZSet().add(
//                redisKey,
//                message.getId().toString(),
//                message.getCreateTime().getTime()
//        );


    }

    /**
     * 房东确认预约
     * @param id
     */
    @Override
    public void confirmAppointment(Integer id) {
        Appointment appointment = appointmentMapper.selectById(id);
        if (appointment.getStatus() != 0){
            throw new CustomException("500","该预约已处理，请勿重复操作");
        }
        appointment.setStatus(1);
        appointmentMapper.updateStatus(appointment);
        //通知用户
        Room room = roomMapper.selectById(appointment.getRoomId());
        Owner owner = ownerMapper.selectById(room.getOwnerId());
        Message message = new Message(
                "user",
                appointment.getUserId(),
                "system-appointment",
                appointment.getId(),
                String.format("房东已确认您的预约：%s，请保持电话畅通,房东联系电话：%s",
                        room.getName(),owner.getPhone())
        );

        messageMapper.insert(message);

        //webSocket推送
        webSocketService.sendMessageToUser(message);
    }

    @Override
    public Boolean isAppointment(Integer userId, Integer roomId) {
        // 检查近期是否已预约
       LocalDateTime now = LocalDateTime.now();
       LocalDateTime lastTime = now.minusDays(1);//设置一天内不可重复预约
        return appointmentMapper.existsByUserAndRoom(
                userId,
                roomId,
                lastTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        ) > 0;
    }



    /**
     * 根据id查询预约
     *
     * @param id
     * @return
     */
    @Override
    public Appointment selectById(Integer id) {
        Appointment appointment = appointmentMapper.selectById(id);
        return appointment;
    }

    /**
     * 获取待处理的预约数量
     *
     * @return
     */
    @Override
    public int unProcessedCount(Integer ownerId) {
        return appointmentMapper.unProcessedCount(ownerId);
    }

    /**
     * 取消预约
     *
     * @param id
     * @param cancelReason
     */
    @Override
    public void cancelAppointment(Integer id, String cancelReason) {
        // 检查是否存在该预约
        Appointment appointment = appointmentMapper.selectById(id);
        if (appointment == null) {
            throw new CustomException("404", "未找到该预约");
        }
        if (appointment.getStatus() != 0){
            throw new CustomException("500","该预约已处理，请勿重复操作");
        }
        // 更新状态和取消原因
        appointment.setStatus(3);
        appointment.setCancelReason(cancelReason);

        // 更新数据库
        appointmentMapper.cancelAppointment(appointment);

        // 通知用户、房东
        Room room = roomMapper.selectById(appointment.getRoomId());
        Integer ownerId = room.getOwnerId();
        Message messageToUser = new Message(
                "user",
                appointment.getUserId(),
                "system-appointment",
                appointment.getId(),
                String.format("预约已取消：%s，原因：%s",
                        room.getName(),cancelReason)
        );
        messageMapper.insert(messageToUser);
        Message messageToOwner = new Message(
                "owner",
                ownerId,
                "system-appointment",
                appointment.getId(),
                String.format("预约已取消：%s，原因：%s",
                        room.getName(),cancelReason)
        );
        messageMapper.insert(messageToOwner);

        //webSocket推送
//        webSocketService.sendMessageToOwner(message);
    }

    /**
     * 删除
     *
     * @param
     */
    @Override
    public void deleteById(Integer userId, Integer roomId) {
         appointmentMapper.deleteById(userId,roomId);
    }


    /**
     * 查询所有预约
     *
     * @return
     */
    @Override
    public List<Appointment> selectAll(Integer userId, String role) {
        if (role.equals("user")){
           return appointmentMapper.selectAll(userId,null,role);
        }else if (role.equals("owner")){
           return appointmentMapper.selectAll(null,userId,role);
        }
        throw new CustomException("500","预约错误---无效的用户类型");
    }


    /**
     * 分页查询
     *
     * @param pageNum  查询哪一页
     * @param pageSize 一页的大小
     * @return
     */
    @Override
    public PageInfo<Appointment> selectPage(Appointment appointment,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
//        List<Appointment> list = appointmentMapper.selectAll(appointment);
        List<Appointment> list = null;
        return PageInfo.of(list);
    }
}
